@extends('user.base')
@section('content-header','Edit Photo')
@section('content-body')
<div id="drawingCanvas" >
	<canvas id="lower-Canvas">
	</canvas>
	<img src='{{ asset("$photo->pic_url")}}' id="patientImg" hidden="true"/>
</div>
<div class="col-md-9" style="padding-top: 10px;">
	<ul>
		<li type="button" class=" btn btn-primary" id="draw_rect" >
			draw_rect
		</li>
		<li type="button" class=" btn btn-primary" value="draw_circle" id="draw_circle" >
			draw_circle
		</li>
		<li type="button" class=" btn btn-primary" value="draw_line" id="draw_line">
			draw_line
		</li>
		<li type="button" class=" btn btn-primary" value="draw_angle" id="draw_angle">
			draw_angle
		</li>
		<li type="button" class=" btn btn-primary" value="2" id ="zoom1x">
			1X
		</li>
		<li type="button" class=" btn btn-primary" value="2" id ="zoom2x">
			2X
		</li>
		<li type="button" class=" btn btn-primary" value="4" id ="zoom4x">
			<span>4X</span>
		</li>
		<li type="button" class=" btn btn-primary" id="remove">
			Remove
		</li>
		<li type="button" class="btn btn-primary" id="btnSave">
			Save
		</li>
		<li type="button" class="btn btn-primary" id="btnLoad">
			Load
		</li>
	</ul>
</div>
<div class="col-md-3">
	<span>
		<input type="color" style="display: block;" id='colorPicker'>
	</span>
</div>
@endsection
@section('js')
<script type="text/javascript">function drawLine(canvas, color, scalePerPixel) {
	var penColor = arguments[1] ? arguments[1] : '#000000';
	var length = 1;
	var coords = [250, 125, 500, 225];
	var line = new fabric.Line(coords, {
		stroke: penColor,
	});
	var label = new fabric.Text("", {
		fontSize: 16,
		fontFamily: "Open Sans",
	});
	length = Math.sqrt(line.getBoundingRectHeight() * line.getBoundingRectHeight() + line.getBoundingRectWidth() * line.getBoundingRectWidth()) * scalePerPixel;
	label.set({
		left: line.left + 0.5 * (line.x2 - line.x1),
		top: line.top + 0.25 * (line.y2 - line.y1),
		text: length.toFixed(2) + "mm",
	});
	var group = new fabric.Group([line, label], {
		left: line.x1,
		top: line.y1,
	});
	group.set({
		borderColor: 'red',
		cornerColor: 'green',
		cornerSize: 6,
		transparentCorners: false,
	});
	group.on('modified', function() {
		length = Math.sqrt(group.getBoundingRectHeight() * group.getBoundingRectHeight() + group.getBoundingRectWidth() * group.getBoundingRectWidth()) * scalePerPixel;
		group.item(1).set({
			text: length.toFixed(2) + "mm",
			left: group.left + group.getBoundingRectWidth() * 0.5,
			top: group.top + group.getBoundingRectHeight() * 0.25,
		});
	});
	canvas.add(group);
}

function drawCircle(canvas, color, scalePerPixel) {
	var penColor = arguments[1] ? arguments[1] : '#000000';
	var xradius;
	var yradius;
	var circle = new fabric.Circle({
		radius: 100,
		left: 100,
		top: 100,
		radius: 70,
		fill: 'rgba(0,0,0,0)',
		stroke: penColor,
	});
	xradius = circle.getBoundingRectWidth() * 0.5;
	yradius = circle.getBoundingRectHeight() * 0.5;
	var xlabel = new fabric.Text("", {
		fontSize: 16,
		fontFamily: "Open Sans",
	});
	xlabel.set({
		left: circle.left + circle.radius + 20,
		top: circle.top + circle.radius,
		text: xradius + "mm",
	});
	xlabel.selectable = false;
	var ylabel = new fabric.Text("", {
		fontSize: 16,
		fontFamily: "Open Sans",
	});
	ylabel.set({
		left: circle.left + circle.radius,
		top: circle.top + circle.radius + 20,
		text: yradius + "mm",
	});
	ylabel.selectable = false;
	var group = new fabric.Group([circle, xlabel, ylabel], {
		left: circle.left,
		top: circle.top,
	});
	group.set({
		borderColor: 'red',
		cornerColor: 'green',
		cornerSize: 6,
		transparentCorners: false
	});
	group.on('modified', function() {
		xradius = group.getBoundingRectWidth() * 0.5;
		yradius = group.getBoundingRectHeight() * 0.5;
		group.item(1).set({
			text: xradius.toFixed(2) + "mm",
		});
		group.item(2).set({
			text: yradius.toFixed(2) + "mm",
		});
	});
	canvas.add(group);
}

function drawRect(canvas, color, scalePerPixel) {
		var penColor = arguments[1] ? arguments[1] : '#000000';
		var xradius;
		var yradius;
		var r = new fabric.Rect({
			left: 100,
			top: 100,
			width: 200,
			height: 200 * 0.618,
			fill: 'rgba(0,0,0,0)',
			stroke: penColor,
		});
		r.hasRotatingPoint = true;
		var labelHeight = new fabric.Text("", {
			fontSize: 16,
			fontFamily: "Open Sans",
		});
		labelHeight.set({
			left: r.left,
			top: r.top + 0.5 * r.height,
			text: 200 * 0.618 * scalePerPixel + "mm",
		});
		labelHeight.selectable = false;
		var labelWidth = new fabric.Text("", {
			fontSize: 16,
			fontFamily: "Open Sans",
		});
		labelWidth.set({
			left: r.left + (r.width / 2 - 10),
			top: r.top,
			text: 200 * scalePerPixel + "mm",
		});
		var group = new fabric.Group([r, labelHeight, labelWidth], {
			left: r.left,
			top: r.top,
		});
		group.set({
			borderColor: 'red',
			cornerColor: 'green',
			cornerSize: 6,
			transparentCorners: false
		});
		group.on('modified', function() {
			height = group.getBoundingRectHeight() * scalePerPixel;
			width = group.getBoundingRectWidth() * scalePerPixel;
			group.item(1).set({
				text: height.toFixed(2) + "mm",
			});
			group.item(2).set({
				text: width.toFixed(2) + "mm",
			});
		});
		canvas.add(group);
	}
	/*
	@lineFrom: line comes from left;
	@lineTo; line goes to right;
	* */

function makeCircle(left, top, lineA, lineB, lineC, lineD) {
	var c = new fabric.Circle({
		left: left,
		top: top,
		strokeWidth: 2,
		radius: 5,
		fill: '#fff',
		stroke: '#666',
		originX: 'center',
		originY: 'center',
	});
	c.hasControls = c.hasBorders = false;
	c.lineA = lineA;
	c.lineB = lineB;
	c.lineC = lineC;
	c.lineD = lineD;
	c.on('moving', function(e) {
		c.lineA && c.lineA.set({
			'x2': c.left,
			'y2': c.top,
		});
		c.lineB && c.lineB.set({
			'x1': c.left,
			'y1': c.top,
		});
		c.lineC && c.lineC.set({
			'x1': c.left,
			'y1': c.top,
		});
		c.lineD && c.lineD.set({
			'x1': c.left,
			'y1': c.top,
		});
	});
	return c;
}

function makeLine(coords, color) {
	var line = new fabric.Line(coords, {
		fill: 'red',
		stroke: color,
		strokeWidth: 2,
		selectable: false,
		originX: 'center',
		originY: 'center',
	});
		
	return line;
}

/**
 * alter angel label
 */
function setAngle(pointA, pointB, pointC, label) {
	dx1 = pointA.left - pointB.left;
	dy1 = pointA.top - pointB.top;
	dx2 = pointA.left - pointC.left;
	dy2 = pointA.top - pointC.top;
	c = Math.sqrt(dx1 * dx1 + dy1 * dy1) * Math.sqrt(dx2 * dx2 + dy2 * dy2);
	degree = (Math.acos((dx1 * dx2 + dy1 * dy2) / c) * 57.3).toFixed(1);
	label.set({
		top: pointA.top,
		left: pointA.left,
		text: degree + '°',		
	});
	return degree;
}

function drawAngle(canvas, color, scalePerPixel) {
	var penColor = arguments[1] ? arguments[1] : '#000000';
	var angleInDegree;
	xcoord = [200, 200, 300, 200];
	ycoord = [200, 200, 300, 150];
	var lineA = makeLine(xcoord, color);
	var lineB = makeLine(ycoord, color);
	pointA = makeCircle(200, 200, null, lineA, lineB);
	pointB = makeCircle(300, 200, lineA);
	pointC = makeCircle(300, 150, lineB);
	var angle = new fabric.Text("", {
		fontSize: 16,
		fontFamily: "Open Sans",
		originX: 'left',
		originY: 'top',
		stroke: color,
		selectable:false,
	});
	setAngle(pointA, pointB, pointC, angle);
	canvas.add(lineA, lineB);
	canvas.add(pointA, pointB, pointC);
	canvas.add(angle);
	pointA.on('moving', function() {
		setAngle(pointA, pointB, pointC, angle);
	});
	pointB.on('moving', function() {
		setAngle(pointA, pointB, pointC, angle);
	});
	pointC.on('moving', function() {
		setAngle(pointA, pointB, pointC, angle);
	});	
	
}
$(function() {
	var globscale = 1;
	var selectObj;
	var enlargeFactor = 1.0;
	var color = "#000000";
	var width = document.getElementById("drawingCanvas").offsetWidth;
	var height = document.documentElement.offsetHeight * 0.75;
	var canvas = new fabric.Canvas('lower-Canvas');
	var scalePerPixel = 1;
	var startX;
	var startY;
	var cursorX;
	var cursorY;
	var positionUp;
	canvas.setHeight(height);
	canvas.setWidth(width);
	canvas.on({
		'object:selected': getObject,
		'object:modified': updateObject,
		'mouse:down':zooming,
		'selection:cleared':clearSelection,		
	});
	var imgElement = document.getElementById("patientImg");
	var imgInstance = new fabric.Image(imgElement, {
		left: 0,
		top: 0,
		opacity: 0.85,
	});
	imgInstance.width = width;
	imgInstance.height = height;
	imgInstance.selectable = false;
	canvas.on('object:moving', function(e) {
		
	});
	canvas.on('mouse:up', function(e) {
		
	});
	canvas.add(imgInstance);
	
	/**
	 * remove canvas objects via id
	 */
	function getObject(e) {
			selectObj = e.target;
			if(selectObj.type =='image'){
				
			}
					
		}
		
	/**
	 * update canvas object coordinates
	 */
	function updateObject(e) {
		obj = e.target;
		obj.setCoords();
		
	}
	
	function clearSelection(e){
		selectObj = null;
	}
	
	function zooming(e,factor){
		console.log(event.clientX);
	}
	$("#draw_rect").bind("click", function() {
		drawRect(canvas, color, scalePerPixel / globscale);
	});
	$("#draw_circle").bind("click", function() {
		drawCircle(canvas, color, scalePerPixel / globscale);
	});
	$("#draw_line").bind("click", function() {
		drawLine(canvas, color, (scalePerPixel / globscale));
	});
	$("#draw_angle").bind("click", function() {
		drawAngle(canvas, color, scalePerPixel);
	});
	$("#remove").bind("click", function() {
		canvas.remove(selectObj);
	});
	$("#zoom2x").bind("click", function() {
		var objects = canvas.getObjects();
		for (var i in objects) {
			objects[i].scaleToHeight(objects[i].getBoundingRectHeight() * 2 / globscale).set({
				left: objects[i].left * 2 / globscale,
				top: objects[i].top * 2 / globscale,
			});
			objects[i].setCoords();
		}
		globscale = 2;
		canvas.renderAll();
	});
	$("#zoom4x").bind("click", function() {
		var objects = canvas.getObjects();
		for (var i in objects) {
			objects[i].scaleToHeight(objects[i].getBoundingRectHeight() * 4 / globscale).set({
				left: objects[i].left * 4 / globscale,
				top: objects[i].top * 4 / globscale,
			});
			objects[i].setCoords();
		}
		globscale = 4;
		canvas.renderAll();
	});
	$("#zoom1x").bind("click", function() {
		var objects = canvas.getObjects();
		for (var i in objects) {
			objects[i].scaleToHeight(objects[i].getBoundingRectHeight() * 1 / globscale).set({
				left: objects[i].left * 1 / globscale,
				top: objects[i].top * 1 / globscale,
			});
			objects[i].setCoords();
		}
		globscale = 1;
		imgInstance.selectable = false;
		canvas.renderAll();
	});
	$("#colorPicker").bind("change", function() {
		color = this.value;
	});
	$("#btnSave").on("click", function() {
		$.ajax({
			type: "POST",
			url: "http://localhost:8080/api/upload/updatePic",
			dataType: 'text',
			data: {
				id: {{ $photo->id }},
				canvasInfo: JSON.stringify(canvas)
			},
			success: function(data) {
				alert(data);
			},
			error: function(data, errorMessage) {
				alert(errorMessage);
			}
		});
	});
	$(document).ready(function() {
		$.ajax({
			type: "POST",
			url: "http://localhost:8080/api/upload/loadPic",
			dataType: 'JSON',
			data: {
				id: {{$photo->id}},
			},
			success: function(data) {				
				canvas.loadFromJSON(data, canvas.renderAll.bind(canvas),function(o,object){
					switch(o.type){
						case "image":
							console.log(o,object);
							canvas.setBackgroundImage(o.src);
							object.selectable = false;
						break;
						case "line":
						case "text":				
						case "circle":
						case "group":												
						default:
							console.log(object.type);						
					}						
				});							
			},
			error: function(data, errorMessage) {
				console.log(errorMessage);
			},
			timeout: 3000,
		});
	});
	$(window).unload(function(){
		$.ajax({
			type: "POST",
			url: "http://localhost:8080/api/upload/updatePic",
			dataType: 'text',
			data: {
				id: {{ $photo->id }},
				canvasInfo: JSON.stringify(canvas),
			},
			success: function(data) {
				alert(data);
			},
			error: function(data, errorMessage) {
				alert(errorMessage);
			}
		});
	});
});</script>
@endsection
